<template>
  <view class="word-learning-page">
    <!-- 顶部导航栏 -->
    <view class="top-nav">
      <view>
        <text>抗遗忘复习（共{{ displayedWords.length }}词）</text>
      </view>
      <view class="top-nav__right">
        <!-- 发音切换 (美式/英式) -->
        <u-button
            class="nav-btn accent-btn"
            :custom-style="accentBtnStyle"
            @click="toggleAccent"
        >
          <text>{{ isAmerican ? '美音' : '英音' }}</text>
        </u-button>

        <!-- 音标显示/隐藏 -->
        <u-button
            class="nav-btn phonetic-btn"
            :custom-style="phoneticBtnStyle"
            @click="togglePhonetic"
        >
          <text :class="['phonetic-label', { 'is-off': !showPhonetic }]">音标</text>
        </u-button>
      </view>
    </view>

    <!-- 中间滚动列表区域 -->
    <scroll-view class="word-list-container" scroll-y>
      <view v-if="displayedWords.length > 0" class="word-list">
        <view
            v-for="(word, index) in displayedWords"
            :key="index"
            class="word-item"
            :class="{
            'word-known': word.status === 'known',
            'word-unknown': word.status === 'unknown'
          }"
            @click="playPronunciation(word, index)"
        >
          <!-- 单词和音标 -->
          <view class="word-info">
            <view class="word-main">
              <view class="word-text">
                <text
                    @click.stop="playEn(word.fullSpell ? word.fullSpell : word.wordFullSpell ? word.wordFullSpell : 'I don\'t know')"
                >{{ word.fullSpell ? word.fullSpell : word.wordFullSpell ? word.wordFullSpell : '🤔' }}
                </text>
              </view>
              <text v-if="showPhonetic" class="word-phonetic">
                {{ isAmerican ? word.phoneticAm : word.phoneticBr }}
              </text>

              <!-- 单词意思 -->
              <view v-if="word.clickCount % 3 === 2" class="word-meaning">
                <text @click.stop="playZh(word.wordMeaning.replace(/[A-Za-z]/g, ''))">{{ word.wordMeaning }}</text>
              </view>
            </view>

            <!-- 添加短语例句按钮 -->
            <view class="phrase-btn-wrap">
              <i class="fa-solid fa-book-open" v-if="word.extendedInfo" @click.stop="showPhraseExample(word)"></i>

              <i :class="{ 'fa-regular fa-heart':word.status !== 'unknown', 'unknown-btn fa-solid fa-heart': word.status === 'unknown' }"
                 :custom-style="quickBtnStyle(word)"
                 @click.stop="toggleUnknown(index)"></i>
            </view>
          </view>
        </view>
      </view>
      <view v-else>
        <u-empty text="这里空空的" mode="list"></u-empty>
      </view>
    </scroll-view>

    <!-- 底部统计栏 -->
    <view class="bottom-nav">
      <view>
        <text>遗忘 {{ unknownCount }} 个单词</text>
      </view>
      <view class="word-actions">
        <!-- 不认识 -->
        <view class="not-learn">
          <text>😔</text>
          <text class="badge">{{ unknownCount }}</text>
        </view>
      </view>
      <view class="div-btns">
        <view class="checkbox-label">
          <checkbox :checked="canKnowWord" @click="onCheckboxChange" class="checkbox-input"/>
          <text class="checkbox-text">屏蔽已认识</text>
        </view>
        <u-button
            class="nav-btn start-learn"
            size="medium"
            :disabled="displayedWords.length === 0"
            @click="submitCheckData"
        >
          <i class="fa-solid fa-floppy-disk"/>
          提交结果
        </u-button>
      </view>
    </view>

    <word-detail-drawer
        :word="currentWordDetail"
        :visible="drawer"
        @update:visible="drawer = false"
        style="max-height: 0px"
    />
  </view>
</template>

<script>
import {courseAfter} from '@/api/wordSystemCourse'
import AudioCacheUtil from '@/utils/AudioCacheUtil'
import {antiForgetListPush} from '@/api/antiForget'
import WordDetailDrawer from '@/pages/components/WordDetailDrawer.vue'
import View from "../component/view/view.vue";

export default {
  name: 'AntiForgetReview',
  components: {View, WordDetailDrawer},
  data() {
    return {
      isAmerican: true, // 美式发音
      showPhonetic: true, // 显示音标
      playbackSpeed: 1.0, // 播放速度
      showSpeedSlider: false,

      // 单词数据
      displayedWordsBack: [], // 显示的单词备份
      displayedWords: [], // 显示的单词

      nowClickWord: {},
      canKnowWord: true, // 屏蔽单词与否

      currentWordDetail: {},
      drawer: false
    }
  },
  computed: {
    unknownCount() {
      return this.displayedWords.filter(w => w.status === 'unknown').length
    },
    accentBtnStyle() {
      return {
        padding: '8px 12px',
        borderRadius: '20px',
        backgroundColor: this.isAmerican ? '#e6f4ea' : '#148c63',
        color: this.isAmerican ? '#239744' : '#ffffff',
        border: this.isAmerican ? '1px solid #d1e7dd' : '1px solid transparent'
      }
    },
    phoneticBtnStyle() {
      return {
        padding: '8px 12px',
        borderRadius: '20px',
        backgroundColor: 'transparent',
        border: '1px solid transparent'
      }
    }
  },
  watch: {
    nowClickWord(newValue, oldValue) {
      if (newValue.id !== oldValue.id) {
        oldValue.clickCount = 0
      }
    },
    canKnowWord(newValue) {
      if (newValue) {
        this.displayedWords = this.displayedWordsBack.filter(item => item.knowNoStudy === '0')
      } else {
        this.displayedWords = this.displayedWordsBack
      }
    }
  },
  onLoad(options) {
    this.cid = options.cid
    this.antiForgetId = options.q1
    this.loadWordData()
  },
  onUnload() {
    document.removeEventListener('click', this.handleClickOutside)
  },
  methods: {
    quickBtnStyle(word) {
      const baseStyle = {
        width: '36px',
        height: '36px',
        padding: '0',
        borderRadius: '50%',
        backgroundColor: 'transparent',
        border: '1px solid #ccc',
        color: '#555'
      }

      if (word.status === 'unknown') {
        return {
          ...baseStyle,
          backgroundColor: '#e53e3e',
          color: '#fff',
          borderColor: '#e53e3e'
        }
      }

      return baseStyle
    },

    onCheckboxChange() {
      this.canKnowWord = !this.canKnowWord
    },

    showPhraseExample(word) {
      this.drawer = true
      this.currentWordDetail = word
    },

    async loadWordData() {
      const res = await courseAfter({cid: this.cid})
      res.studyWordList.forEach(item => {
        item.clickCount = 0
        item.status = ''
      })
      this.displayedWordsBack = res.studyWordList
      this.displayedWords = []
      if (this.canKnowWord) {
        this.displayedWords = res.studyWordList.filter(item => item.knowNoStudy === '0')
      } else {
        this.displayedWords = res.studyWordList
      }
    },

    async submitCheckData() {
      const idArr = []
      this.displayedWords.forEach(item => {
        if (item.status === 'unknown') {
          idArr.push(item.libraryTypeWordId)
        }
      })
      await antiForgetListPush(
          {
            antiForgetId: this.antiForgetId,
            cid: this.cid
          },
          idArr
      )

      uni.redirectTo({
        url: `/pages/system-frame`
      })
    },

    toggleAccent() {
      this.isAmerican = !this.isAmerican
    },

    togglePhonetic() {
      this.showPhonetic = !this.showPhonetic
    },

    playPronunciation(word) {
      AudioCacheUtil.play(word.fullSpell ? word.fullSpell : word.wordFullSpell ? word.wordFullSpell : 'I don\'t know', this.isAmerican ? 'en' : 'uk', this.playbackSpeed)
      word.clickCount++
      this.nowClickWord = word
    },

    playZh(text) {
      AudioCacheUtil.play(text, 'zh', this.playbackSpeed)
    },

    playEn(text) {
      AudioCacheUtil.play(text, this.isAmerican ? 'en' : 'uk', this.playbackSpeed)
    },

    handleClickOutside(e) {
      // 在uni-app中可能需要适配不同的DOM获取方式
      const controlEl = this.$refs.speedControlRef
      if (controlEl && !controlEl.$el.contains(e.target)) {
        this.showSpeedSlider = false
        document.removeEventListener('click', this.handleClickOutside)
      }
    },

    toggleUnknown(index) {
      const word = this.displayedWords[index]
      if (word.status === 'unknown') {
        word.status = null
      } else {
        word.status = 'unknown'
      }
    }
  }
}
</script>

<style scoped>
* {
  user-select: none;
}

.word-learning-page {
  display: flex;
  flex-direction: column;
  height: calc(100vh - 50px);
  width: 100vw;
  overflow: hidden;
  background-color: #f5f7fa;
}

/* 中间单词列表区域 */
.word-list-container {
  flex: 1;
  overflow: hidden;
  padding: 5px;
}

.word-list {
  height: 100%;
}

.word-info {
  display: flex;
  align-items: center;
  margin-bottom: 12px;
  user-select: none;
}

.word-main {
  flex: 1;
}

.word-text {
  font-size: 32px;
  font-weight: 700;
  margin: 0 0 4px 0;
  color: #2c3e50;
  font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif;
  width: 100%;
  position: relative;
}

.word-text text {
  cursor: pointer;
}

.word-phonetic {
  font-size: 18px;
  color: #999;
  margin: 10px 0 0 0;
  font-style: italic;
  display: block;
}

.word-meaning {
  color: #555;
  margin-top: 20px;
}

.word-meaning text {
  cursor: pointer;
}

.phrase-btn-wrap {
  display: flex;
  margin: 0 8px;
  gap: 5rpx;
  font-size: 40rpx;

  * {
    cursor: pointer;
  }
}

.fa-book-open {
  color: #206a95;
}

.fa-heart {
  color: #c84f4f;
}

/* 底部菜单栏 */
.bottom-nav {
  display: flex;
  justify-content: space-between;
  padding: 0 20px;
  align-items: center;
  height: 56px;
  background-color: #fff;
  box-shadow: 0 -2px 8px rgba(0, 0, 0, 0.1);
}

/* 顶部导航栏整体样式 */
.top-nav {
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding: 0 16px;
  height: 50px;
  background-color: #fff;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
  z-index: 10;
  position: relative;
}

.top-nav__right {
  display: flex;
  align-items: center;
  gap: 12px;
}

.nav-btn {
  border-radius: 20px;
  background-color: transparent;
  color: #333;
  border: 1px solid transparent;
  font-size: 14px;
}

.start-learn {
  border: 1px solid #e0e0e0;
}

.start-learn:hover {
  color: #0084ff;
}

.phonetic-label {
  width: 32px;
  position: relative;
  display: inline-block;
  padding: 0 2px;
  color: #333;
  transition: color 0.2s ease;
}

.phonetic-label::after {
  content: "";
  position: absolute;
  left: 0;
  right: 0;
  height: 2px;
  top: 50%;
  transform: translateY(-50%) scaleX(0);
  transform-origin: left center;
  background: #ff4d4f;
  transition: transform 0.25s cubic-bezier(.2, .9, .2, 1);
  pointer-events: none;
}

.phonetic-label.is-off {
  color: #999;
}

.phonetic-label.is-off::after {
  transform: translateY(-50%) scaleX(1);
}

@keyframes fadeIn {
  from {
    opacity: 0;
    transform: translateY(-10px);
  }
  to {
    opacity: 1;
    transform: translateY(0);
  }
}

.word-item {
  background-color: #fff;
  border-radius: 12px;
  padding: 10px;
  margin-top: 16px;
  box-shadow: 0 2px 10px rgba(0, 0, 0, 0.05);
  transition: all 0.3s ease;
}

.word-item.word-known {
  background-color: #e6f7ed;
  border: 1px solid #239744;
}

.word-item.word-unknown {
  background-color: #fde2e2;
  border: 1px solid #e53e3e;
}

.word-actions {
  display: flex;
  gap: 40px;
  margin-top: 12px;
  margin-bottom: 12px;
  position: relative;
}

.word-actions > view {
  position: relative;
  font-size: 40px;
}

.not-learn {
  color: rgb(229, 62, 62);
}

.badge {
  position: absolute;
  top: -6px;
  right: -10px;
  min-width: 20px;
  height: 20px;
  padding: 0 6px;
  border-radius: 10px;
  background-color: #ff4d4f;
  color: #fff;
  font-size: 12px;
  font-weight: bold;
  line-height: 20px;
  text-align: center;
}

.not-learn .badge {
  background-color: #ff4d4f;
}

.div-btns {
  width: 350rpx;
  display: flex;
  flex-direction: row;
  align-items: center;
}

.checkbox-label {
  display: flex;
  width: 300rpx;
  align-items: center;
  cursor: pointer;
  gap: 2px;
  font-size: 14px;
  color: #333;
  transition: color 0.2s ease;
}

.checkbox-input {
  border-radius: 4px;
}

.checkbox-input:checked {
  background-color: #34a853;
}

.checkbox-text {
  color: inherit;
}

.word-item:hover {
  transform: translateY(-2px);
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
  background-color: #00b578;
}

.word-item:hover text,
.word-item:hover .word-text {
  color: white;
}
</style>
